package org.galaxyworld.flycode.jobs;

import org.apache.commons.lang3.StringUtils;
import org.galaxyworld.flycode.config.AppConfigData;
import org.galaxyworld.flycode.config.ConfigManager;
import org.galaxyworld.flycode.config.JdbcConfigData;

import java.sql.*;

public class ModelGenerator extends AbstractDatabaseGenerator {

    @Override
    protected void doWithConnection(Connection connection) throws SQLException {
        AppConfigData appConfigData = ConfigManager.getConfig(AppConfigData.class);
        JdbcConfigData jdbcConfigData = ConfigManager.getConfig(JdbcConfigData.class);
        DatabaseMetaData dmd = connection.getMetaData();
        ResultSet tables = dmd.getTables(
                connection.getCatalog(), StringUtils.upperCase(jdbcConfigData.getUserName()),
                null, new String[]{"TABLE", "VIEW"});
        showMessage("Read done.", "Start generating...");
        while (tables.next()) {
            Model model = new Model();
            String tableName = tables.getString("TABLE_NAME");
            // get columns
            ResultSet columns = dmd.getColumns(connection.getCatalog(), StringUtils.upperCase(jdbcConfigData.getUserName()), tableName, "%");
            while (columns.next()) {
                int type = columns.getInt("DATA_TYPE");
                String name = columns.getString("COLUMN_NAME");
                Field field = new Field();
                field.setTypeId(type, appConfigData.isJava8Enabled());
                field.setColumnName(name);
                model.addField(field);
                if (type == Types.DATE
                        || type == Types.TIME
                        || type == Types.TIMESTAMP) {
                    model.setHasDateType(true);
                }
                if (field.isKeyword()) {
                    model.setHasKeywords(true);
                }
            }
            columns.close();
            model.setTableName(tableName);
            // get primary keys
            ResultSet pk = dmd.getPrimaryKeys(connection.getCatalog(), StringUtils.upperCase(jdbcConfigData.getUserName()), tableName);
            while (pk.next()) {
                for (Field field : model.getFields()) {
                    if (StringUtils.equals(field.getColumnName(), pk.getString("COLUMN_NAME"))) {
                        field.setPrimaryKey(true);
                        model.addPrimaryKey(field);
                    }
                }
            }
            pk.close();
            // get foreign keys
//            ResultSet fk = dmd.getExportedKeys(connection.getCatalog(), StringUtils.upperCase(jdbcConfigData.getUserName()), tableName);
//            while (fk.next()) {
//                System.out.println(fk.getString("FKTABLE_NAME"));
//                System.out.println(fk.getString("FKCOLUMN_NAME"));
//            }
//            fk.close();
            model.saveToFile();
            showMessage(tableName + " created.");
        }
        tables.close();
    }
}
